<template>
	<el-drawer
		v-model="drawerVisible"
		@closed="cancelForm(ruleFormRef)"
		:destroy-on-close="true"
		:close-on-click-modal="false"
		size="50%"
		:title="`${drawerProps.title}用户`"
	>
		<el-form
			ref="ruleFormRef"
			:model="userInfoForm"
			:rules="rules"
			label-width="120px"
			label-position="left"
			class="demo-ruleForm"
			status-icon
		>
			<el-form-item label="姓名：" prop="userName">
				<el-input :disabled="drawerProps.title == '编辑'" v-model="userInfoForm.userName" placeholder="请输入姓名" type="text" />
			</el-form-item>
			<el-form-item required label="所属商户：" v-if="!isPlatform">
				<el-select v-model="userInfoForm.selectCompany" placeholder="所属商户" @change="getRoleNameList">
					<el-option v-for="item in CompanyInfo" :key="item.CompanyId" :label="item.CompanyName" :value="item.CompanyId" />
				</el-select>
			</el-form-item>
			<el-form-item label="手机号码：" prop="userTel">
				<el-input v-model.number="userInfoForm.userTel" maxlength="11" placeholder="请输入手机号" />
			</el-form-item>
			<el-form-item label="登录账号：" prop="loginName">
				<el-input v-model="userInfoForm.loginName" type="text" placeholder="请输入账号" />
			</el-form-item>
			<el-form-item v-if="isPlatRole" label="员工角色：" prop="roleId">
				<el-select v-model="userInfoForm.roleId" placeholder="选择角色">
					<el-option v-for="item in roleInfo" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
				</el-select>
				<div style="margin-left: 10px; color: #d8d8d8">如未设置角色则登录后无操作权限</div>
			</el-form-item>
			<el-form-item label="出生日期：" prop="userDateOfBirth">
				<el-date-picker
					v-model="userInfoForm.userDateOfBirth"
					type="date"
					placeholder="选择日期"
					format="YYYY/MM/DD"
					value-format="YYYY-MM-DD"
				/>
			</el-form-item>
			<el-form-item label="性别：" prop="userSex">
				<el-radio-group v-model="userInfoForm.userSex">
					<el-radio label="男" value="男" />
					<el-radio label="女" value="女" />
				</el-radio-group>
			</el-form-item>
			<el-form-item label="状态：" prop="states">
				<el-radio-group v-model="userInfoForm.states">
					<el-radio :label="true">启用</el-radio>
					<el-radio :label="false">禁用</el-radio>
				</el-radio-group>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="cancelForm(ruleFormRef)">取消</el-button>
			<el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">保存</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { reactive, ref, watch, nextTick } from "vue";
import userInfoApi from "@/api/modules/userInfo";
import companyInfoApi from "@/api/modules/companyInfo";
import roleInfoApi from "@/api/modules/roleInfo";
import { GlobalStore } from "@/stores";
const { userInfo, isPlatform } = GlobalStore();
const userInfoForm = ref({
	userName: "", //员工姓名
	selectCompany: "", //商户选择
	companyId: "", //所属商户
	userTel: "", //手机号码
	loginName: "", //登录账号
	userDateOfBirth: "", //出生日期
	roleId: "", //员工角色
	userSex: "男", //性别
	states: true, //启用状态
	id: "" //Id编辑的时候用
});
interface CompanyItem {
	CompanyId: string;
	CompanyName: string;
}
const CompanyInfo = ref<CompanyItem[]>([]);
//获取客户名称集合
const getCompanyNameList = async () => {
	if (userInfo.companyInfo == null) {
		CompanyInfo.value.push({
			CompanyId: "",
			CompanyName: "平台端"
		});
	}
	let { result } = await companyInfoApi.GetCompanyNameList();
	//编辑
	result.data.forEach((element: any) => {
		CompanyInfo.value.push({
			CompanyId: element.id,
			CompanyName: element.companyName
		});
	});
	// 新增
	userInfoForm.value.selectCompany = CompanyInfo.value[0].CompanyId;
};
getCompanyNameList();
//获取角色名称集合
interface RoleItem {
	roleId: string;
	roleName: string;
}
const roleInfo = ref<RoleItem[]>([]);
//获取角色名称信息
const getRoleNameList = async () => {
	//console.log(userInfoForm)
	roleInfo.value = [];
	let { result } = await roleInfoApi.GetRoleNameList({
		CompanyId: userInfoForm.value.selectCompany == "平台端" ? "" : userInfoForm.value.selectCompany
	});
	result.data.forEach((element: any) => {
		roleInfo.value.push({
			roleId: element.id,
			roleName: element.roleName
		});
	});
};
getRoleNameList();
// 判断身份是否是平台身份
const isPlatRole = ref<boolean>(true);
//初始化，如果是编辑，调用接口填入数据
const init = () => {
	//判断是否是编辑
	nextTick(async () => {
		if (!drawerProps.value.id) return;
		let { result } = await userInfoApi.GetUserInfo({ id: drawerProps.value.id });
		let { code, data } = result;
		if (code != 200) return;
		userInfoForm.value = data;
		userInfoForm.value.selectCompany = data.companyId || "";
		isPlatRole.value = data.roleId ? roleInfo.value.filter(i => i.roleId == data.roleId).length > 0 : true;
	});
};
const checkAccount = (rule: any, value: any, callback: any) => {
	if (value === "") callback("请输入登录账号");
	if (drawerProps.value.id) callback();
	userInfoApi.GetLoginUserInfo({ loginName: value, passWord: "" }).then(res => {
		if (res.result.code != 200) {
			callback("登录账号已存在！");
			return;
		}
		callback();
	});
};
const checkPhoneNo = (rule: any, value: any, callback: any) => {
	const regexp = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/;
	if (value === "") callback("请输入手机号码");
	if (!regexp.test(value)) {
		callback(new Error("请输入正确的手机号码"));
	} else {
		if (drawerProps.value.id) callback();
		userInfoApi.VerificationUserTel({ userTel: value }).then(res => {
			if (res.result.code != 200) {
				callback("手机号码已存在！");
				return;
			}
			callback();
		});
	}
};
const rules = reactive<FormRules>({
	userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
	userTel: [
		{ required: true, message: "请输入手机号码", trigger: "blur" },
		{ validator: checkPhoneNo, trigger: "blur" }
	],
	loginName: [
		{ required: true, message: "请输入登录账号", trigger: "blur" },
		{ validator: checkAccount, trigger: "blur" }
	],
	selectCompany: [{ required: false, message: "请选择所属商户", trigger: "change" }],
	states: [{ required: true, message: "请选择状态", trigger: "change" }],
	userDateOfBirth: [{ required: false, message: "请选择生日", trigger: "change" }],
	userSex: [{ required: false, message: "请选择用户性别", trigger: "change" }],
	roleId: [{ required: false, message: "请选择用户权限", trigger: "change" }]
});
interface DrawerProps {
	title: string;
	isView: boolean;
	id: string | null;
	api?: (params: any) => Promise<any>;
	getTableList?: () => void;
}
const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
	isView: false,
	title: "",
	id: ""
});
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
	drawerProps.value = params;
	drawerVisible.value = true;
};
watch(
	() => drawerVisible.value,
	val => {
		if (!val) return;
		init();
	}
);
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const cancelForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	userInfoForm.value.selectCompany = "";
	drawerVisible.value = false;
};
const handleSubmit = () => {
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			userInfoForm.value.companyId = userInfoForm.value.selectCompany == "平台端" ? "" : userInfoForm.value.selectCompany;
			await drawerProps.value.api!(userInfoForm.value);
			ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
			drawerProps.value.getTableList!();
			drawerVisible.value = false;
		} catch (error) {
			console.log(error);
		}
	});
};

defineExpose({
	acceptParams
});
</script>
